﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Roslyn.Compilers.CSharp;
using Roslyn.Services;

namespace Analysis.DependencyGenerators
{
    class CyclematicComplexityGenerator : IGenerator
    {
        public IEnumerable<Dependency> GetBlockDependencies(AnalysisKind kind, BlockSyntax bs, IDocument document)
        {
            var parent = bs.Parent;

            if (!(parent is MethodDeclarationSyntax))
                return new List<Dependency>();

            var nodes = parent.ChildNodes();
            var blocknode = nodes.FirstOrDefault(n => n is BlockSyntax);
            if (blocknode != null)
            {
                var illegalKinds = new List<SyntaxKind> 
                { 
                    SyntaxKind.OrAssignExpression,
                    SyntaxKind.AmpersandAmpersandToken, 
                    SyntaxKind.BreakStatement, 
                    SyntaxKind.CaseSwitchLabel, 
                    SyntaxKind.CatchClause, 
                    SyntaxKind.ContinueStatement, 
                    SyntaxKind.DefaultSwitchLabel, 
                    SyntaxKind.DoKeyword, 
                    SyntaxKind.DoStatement, 
                    SyntaxKind.ElseClause,
                    SyntaxKind.ForEachStatement, 
                    SyntaxKind.ForStatement, 
                    SyntaxKind.GotoCaseStatement, 
                    SyntaxKind.GotoDefaultStatement, 
                    SyntaxKind.GotoStatement, 
                    SyntaxKind.IfStatement, 
                    SyntaxKind.WhileStatement, 
                    SyntaxKind.YieldReturnStatement,
                    SyntaxKind.FinallyClause                
                };

                var foo = blocknode.ChildNodes();
                int complexity = foo.Count(n => illegalKinds.Contains(n.Kind));

                if (complexity > 10)
                    return new List<Dependency> { new Dependency { In = parent, Kind = AnalysisKind.CyclomaticComplexity } };
            }
            return new List<Dependency>();
        }

    }
}
